﻿using System;
using System.Windows.Browser;
using System.Windows;

namespace DXTools.Core
{
    public static class ClientScript
    {
        /// <summary>
        /// Returns the ServerUrl from Microsoft Dynamics CRM
        /// </summary>
        /// <returns>String representing the ServerUrl or String.Empty if not found.</returns>
        public static string GetServerUrl()
        {
            #if(DEBUG)
            if (Application.Current.Host.InitParams.ContainsKey(InitParamsNames.CRM_URL))
                return Application.Current.Host.InitParams[InitParamsNames.CRM_URL];
            else
            {
                if(!IsThereContext())
                    throw new InvalidOperationException("Debug mode needs CRM_URL init parameter or CRM context");
            }
            #endif

            // Post Rollup 12 we can use getClientUrl
            String clientUrl = GetClientUrl();
            if (!String.IsNullOrEmpty(clientUrl))
                return clientUrl;

            // For older orgs pre Rollup 12 use old method.

            string urlPath = HtmlPage.Document.DocumentUri.LocalPath;
            string url = HtmlPage.Document.DocumentUri.ToString();

            string orgName = (string)GetContext().Invoke("getOrgUniqueName");

            int serverURlEnd = url.IndexOf("/", 8);
           // if (serverURlEnd != -1 && url.ToLower().IndexOf(orgName.ToLower(), serverURlEnd) != -1)
            if(!IsCRMOnline())
            {
                // on premise
                url = url.Substring(0, url.IndexOf(urlPath) + 1);
                url += orgName;
            }
            else
            {
                // We are online
                url = (string)GetContext().Invoke("getServerUrl");
                if (url.EndsWith("/"))
                    url = url.Substring(0, url.Length - 1);
            }



            return url;
        }

        public static bool IsOnPremise()
        {
            #if(DEBUG)
                            return true;
            #endif

            bool onPremise = false;

            string url = HtmlPage.Document.DocumentUri.ToString();
            //string orgName = (string)GetContext().Invoke("getOrgUniqueName");

            //int serverURlEnd = url.IndexOf("/", 8);
            //if (serverURlEnd != -1 && url.ToLower().IndexOf(orgName.ToLower(), serverURlEnd) != -1)
            //{
            //    onPremise = true;
            //}
            if (url.ToLower().IndexOf(".dynamics.com") == -1)
            {
                onPremise = true;
            }
            return onPremise;
        }

        public static bool IsCRMOnline()
        {
            bool crmOnline = false;

            string url = HtmlPage.Document.DocumentUri.ToString();

            //if (url.ToLower().IndexOf(".crm.dynamics.com") != -1 | url.ToLower().IndexOf(".crm4.dynamics.com") != -1 | url.ToLower().IndexOf(".crm5.dynamics.com") != -1)
            if (url.ToLower().IndexOf(".dynamics.com") != -1)
            {
                crmOnline = true;
            }
            return crmOnline;
        }

        public static string GetOrganizationName()
        {
            return (string)GetContext().Invoke("getOrgUniqueName");
        }

        public static bool IsThereContext()
        {
            return HtmlPage.Window.GetProperty("Xrm") != null;
        }

        public static ScriptObject GetContext()
        {
            ScriptObject xrmProperty = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
            if (null == xrmProperty)
            {
                //It may be that the global context should be used
                try
                {

                    ScriptObject globalContext = (ScriptObject)HtmlPage.Window.Invoke("GetGlobalContext");

                    return globalContext;
                }
                catch (System.InvalidOperationException)
                {
                    throw new InvalidOperationException("Property \"Xrm\" is null and the Global Context is not available.");
                }

            }

            ScriptObject pageProperty = (ScriptObject)xrmProperty.GetProperty("Page");
            if (null == pageProperty)
            {
                throw new InvalidOperationException("Property \"Xrm.Page\" is null");
            }

            ScriptObject contextProperty = (ScriptObject)pageProperty.GetProperty("context");
            if (null == contextProperty)
            {
                throw new InvalidOperationException("Property \"Xrm.Page.context\" is null");
            }

            return contextProperty;
        }


        public static string GetClientUrl()
        {
            string clientUrl = String.Empty;
            try
            {
                clientUrl = (string)GetContext().Invoke("getClientUrl");

            }
            catch (System.InvalidOperationException)
            {
            }

            return clientUrl;
        }
       
    }
}
